package cn.bonoon.controllers.user;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.bonoon.core.plugins.MessageAcceptService;
import cn.bonoon.core.plugins.MessageService;
import cn.bonoon.entities.plugins.AccountEntity;
import cn.bonoon.entities.plugins.MessageAcceptEntity;
import cn.bonoon.entities.plugins.MessageEntity;
import cn.bonoon.kernel.security.LogonUser;
import cn.bonoon.kernel.support.services.UserService;
import cn.bonoon.kernel.util.MD5Util;
import cn.bonoon.kernel.util.StringHelper;
import cn.bonoon.kernel.web.controllers.AbstractController;
import cn.bonoon.kernel.web.models.JsonResult;

@Controller
@RequestMapping("s/user/msn")
public class UserMessageController extends AbstractController {
	private MessageAcceptService messageAcceptService;
	private MessageService messageService;
	private UserService userService;
	private final String id = MD5Util.randomMD5String();

	@Autowired
	public UserMessageController(MessageAcceptService messageAcceptService, MessageService messageService,
			UserService userService) {
		this.messageAcceptService = messageAcceptService;
		this.messageService = messageService;
		this.userService = userService;
	}
	
	private StringBuffer new_msn() {
		List<MessageAcceptEntity> messageAccept = messageAcceptService.getNewMessage(getUser());
		StringBuffer sb = new StringBuffer();
		for (MessageAcceptEntity entity : messageAccept) {
			MessageEntity message = entity.getMessage();
			sb.append("<tr><td style='padding:0px 0px 0px 5px;color:red;'>").append(message.getSenderName())
			  .append("</td><td style='padding:0px 0px 0px 5px;color:red;'>").append(message.getCreateAt())
			  .append("</td><td style='padding:0px 0px 0px 5px;color:red;'>").append(message.getStatus() == 0 ? "系统消息" : "个人消息")
			  .append("</td><td style='padding:0px 0px 0px 5px;color:red;'>").append(message.getTitle())
			  .append("</td><td style='padding:0px 0px 0px 5px;color:red;'>").append(message.getContent()).append("</td></tr>");
		}
		return sb;
	}

	// 右上角弹出消息对话框
	@RequestMapping("new")
	public String dialog_newMsn(Model model) {
		model.addAttribute("id", id);
		model.addAttribute("attrs", "title='短消息' style='width:700px;height:500px;'");
		model.addAttribute("content", new_msn());
		return "user/message/user-msn-dlg";
	}

	// 显示最新的消息（所有未读消息）
	@RequestMapping("!{key}/index.do")
	public String get(Model model, @PathVariable("key") String key) {
		model.addAttribute("content", new_msn());
		return "user/message/user-msn";
	}

	// 刷新最新消息（所有未读消息）
	@ResponseBody
	@RequestMapping(value = "refreshNewMessage", method = { RequestMethod.GET, RequestMethod.POST })
	public JsonResult refreshNewMessage(Model model) {
		return JsonResult.result(new_msn().toString());
	}
	
	private StringBuffer message(List<MessageAcceptEntity> messageAccept) {
		StringBuffer sb = new StringBuffer();
		for (MessageAcceptEntity entity : messageAccept) {
			MessageEntity message = entity.getMessage();
			sb.append("<tr><td style='padding-left:5px;'>").append(message.getSenderName())
			  .append("</td><td style='padding-left:5px;'>").append(message.getCreateAt())
			  .append("</td><td style='padding-left:5px;'>").append(message.getTitle())
			  .append("</td><td style='padding-left:5px;'>").append(message.getContent())
			  .append("</td></tr>");
		}
		return sb;
	}

	// 系统消息
	@RequestMapping("sys")
	public String msnSys(Model model) {
		Long page = 1L;
		List<MessageAcceptEntity> messageAccept = messageAcceptService.getSysMessage(getUser(), page);
		model.addAttribute("content", message(messageAccept));
		model.addAttribute("page", page);
		return "user/message/user-msn-sys";
	}

	// load更多系统消息
	@ResponseBody
	@RequestMapping(value = "sysLoad", method = { RequestMethod.GET, RequestMethod.POST })
	public JsonResult msnSysLoad(Model model, Long page) {
		List<MessageAcceptEntity> messageAccept = messageAcceptService.getSysMessage(getUser(), ++page);
		return JsonResult.result(message(messageAccept).toString());
	}

	// 个人消息
	@RequestMapping("personal")
	public String msnPersonal(Model model) {
		Long page = 1L;
		List<MessageAcceptEntity> messageAccept = messageAcceptService.getPerMessage(getUser(), page);
		model.addAttribute("content", message(messageAccept));
		model.addAttribute("page", page);
		return "user/message/user-msn-personal";
	}

	// load更多个人消息
	@ResponseBody
	@RequestMapping(value = "personalLoad", method = { RequestMethod.GET, RequestMethod.POST })
	public JsonResult msnPersonalLoad(Model model, Long page) {
		List<MessageAcceptEntity> messageAccept = messageAcceptService.getPerMessage(getUser(), ++page);
		return JsonResult.result(message(messageAccept).toString());
	}
	
	private StringBuffer msn_sended(List<MessageEntity> message) {
		StringBuffer sb = new StringBuffer();
		for (MessageEntity entity : message) {
			List<MessageAcceptEntity> accepts = entity.getAccepts();
			StringBuffer sb_accepts = new StringBuffer();
			for (MessageAcceptEntity accept : accepts) {
				Long accepterId = accept.getAccepterId();
				AccountEntity account = userService.get(accepterId);
				if (null != account) {
					sb_accepts.append(account.getName()).append("、");
				} else {
					sb_accepts.append(accepterId).append("、");
				}
			}
			sb_accepts.deleteCharAt(sb_accepts.length() - 1);
			sb.append("<tr><td style='padding-left:5px;'>").append(entity.getSenderName())
			  .append("</td><td style='padding-left:5px;'>").append(sb_accepts)
			  .append("</td><td style='padding-left:5px;'>").append(entity.getCreateAt())
			  .append("</td><td style='padding-left:5px;'>").append(entity.getTitle())
			  .append("</td><td style='padding-left:5px;'>").append(entity.getContent())
			  .append("</td></tr>");
		}
		return sb;
	}

	// 列出发送消息
	@RequestMapping("send")
	public String msnSend(Model model) {
		Long page = 1L;
		List<MessageEntity> message = messageService.getSendMessage(getUser().getId(), page);
		model.addAttribute("content", msn_sended(message));
		model.addAttribute("page", page);
		return "user/message/user-msn-send";
	}

	// load更多发送消息
	@ResponseBody
	@RequestMapping(value = "sendLoad", method = { RequestMethod.GET, RequestMethod.POST })
	public JsonResult msnSendLoad(Model model, Long page) {
		List<MessageEntity> message = messageService.getSendMessage(getUser().getId(), ++page);
		return JsonResult.result(msn_sended(message).toString());
	}

	// 发送消息
	@RequestMapping("send/save")
	public void msnSendSave(String accepterId, String title, String content) {
		Long[] accepterIds = StringHelper.toLongArray(accepterId, ",");
		LogonUser user = getUser();
		messageService.save(user.getId(), user.getUsername(), title, content, accepterIds);
	}
}
